var rrs = rrs || {};
rrs.shop = rrs.shop || {};
var provinceHtml = provinceHtml || "";
var cityHtml = cityHtml || "";
var regionHtml = regionHtml || "";

$(function(){
    new Settled($);
    $(".js-delete-image").on("click",function(){
    	var $li = $(this).parent().parent().parent();
    	$li.find("img").attr("src","");
    	$li.hide();
    	$li.parent().find(".addbus").show();
    	$li.parent().parent().parent().find("input").val("");
    });
    $(".iswater-select").mouseover(function(){
	    $("#id_shtype").css("display","block");
	});
	$(".iswater-select").mouseout(function(){
	    $("#id_shtype").css("display","none");
	});
	$(".js-show-big-image").click(function(){
		var $li = $(this).parent().parent().parent();
    	var imgSrc = $li.find("img").attr("src");
    	$("#endettle").parent().find("img").attr("src",imgSrc);
 		$(".enlarger_layer").show();
 	});
 	$("#endettle").click(function(){
 		$(".enlarger_layer").hide();
 	});
 	/*$("input[name=customerType]").click(function(){
 		$("#lt-div-id label").hide();
		$('input:radio[name="locationType"]').attr("checked",false);
		$("#lt-div-id label").eq(0).show();
		if($(this).val()==0){
			$("#lt-div-id label").eq(1).show();
			$("#lt-div-id label").eq(2).show();
		}else{
			$("#lt-div-id label").eq(3).show();
			$("#lt-div-id label").eq(4).show();
			$("#lt-div-id label").eq(5).show();
			$("#lt-div-id label").eq(6).show();
		}
	 });*/
});
function setBankAccountName(){
	$("#companyAccountName").val($("#companyName").val());
}
var Settled  = (function() {
    var linkToSeller, that;

    function Settled($) {
        //this.shopNameInput = $("#shop-name");
        this.imageSwitchButton = $(".js-image");
        this.imageSwitchAddBtn = $(".js-add-image");
        this.applyForm = $("#apply-form");
        this.provinceSelect = $(".province-select");
        this.citySelect = $(".city-select");
        this.uploadButton = $("#js-image-upload");
        this.uploadModel = $("#modal-image-selector");
        this.uploadModalCloseBtn = $("#model_close");
        this.modelSubmitBtn = $("#model_submit");
        this.modelImageListUl = $(".modal-body-content ul");
        this.modelCancelBtn = $("#model_cancel");
        this.isWaterSelect = $(".iswater-select");
        //this.modelImageList = $(".modal-body-content ul li")

        // linkToSeller();
        this.bindEvent();
        this.isWaterChange();
    }

    that = Settled;

    Settled.prototype.bindEvent = function() {
        that = this;
        this.applyForm.validator({
         identifier: "input",
         isErrorOnParent: true
         });
        this.provinceSelect.on("change", this.cityChange);
        this.citySelect.on("change", this.regionChange);
        
       // this.shopNameInput.on("focusout", this.shopNameValid);
        this.imageSwitchButton.on("click", this.imageSwitch);
        this.imageSwitchAddBtn.on("click", this.imageSwitch_i);
        this.applyForm.on("submit", this.applyFormSubmit);
        this.isWaterSelect.on("change",this.isWaterChange);
        
        this.uploadModalCloseBtn.on("click", function() {
            $("#currentInput").val("");
            //that.modelImageList.removeClass("active");
            that.uploadModel.hide();
        });

        this.uploadButton.fileupload({
            url: rrs.shopDomain + "/images/uploadFiles",
            dataType: "json",
            done: function (e, data) {
                that.clearImageModel();
                that.loadImageModel();
            }
        });
        
        
        this.modelSubmitBtn.on("click", function() {
            //var modelImageList = $(".modal-body-content ul li");
            var $currentInput = $("#" + $("#currentInput").val());
            var imgSrc = $(".modal-body-content ul li.active img").attr("src");
           // $("#" + $("#currentInput").val()).val(modelImageList.filter(".active").find("img").attr("src"));
            $currentInput.val(imgSrc);
            $currentInput.parent().find(".buspic u li img").attr("src", imgSrc);
            $currentInput.parent().find(".buspic u li").eq(0).show();
            $currentInput.parent().find(".buspic .addbus").hide();
            that.uploadModalCloseBtn.trigger("click");
        });

        this.modelCancelBtn.on("click", function() {
            that.uploadModalCloseBtn.trigger("click");
        })
        return this.provinceChange();
    };

/*    linkToSeller = function() {
        return $.ajax({
            url: "/api/ceiling",
            type: "GET",
            success: function(data) {
                if (data.data.type === 2) {
                    return window.location.href = rrs.shopDomain + "/seller/index";
                } else if (data.data.applySeller !== 0 && data.data.applySeller !== void 0) {
                    return window.location.href = "/user/auditing";
                }
            }
        });
    };*/

    // done
    Settled.prototype.loadImageModel = function() {
        $.ajax({
            url: rrs.shopDomain + "/images/list",
            type: "GET",
            success: function(data) {
                // 取数失败
                if (data == undefined || !data.success) {
                    $.sobox.alert("获取图片列表失败",data.message);
                    return;
                }

                // 不存在用户图片
                if (data.data == undefined || data.data == null) {
                    return;
                }

                that.clearImageModel();

                $.each(data.data.data, function(i, item){
                    var $li = $('<li class=""></li>').attr("id", item.id);
                    var $imageDiv = $('<div class="modal-image"></div>');
                    var $image = $('<img>').attr("src", item.url);
                    var $deleteButtion = $('<button class="btn btn-mini btn-trash js-image-delete" data-id="'+item.id+'">×</button>');

                    $li.bind("click", function(){
                        that.modelImageListUl.find('li').removeClass("active");
                        $(this).addClass("active");
                    });

                    $image.appendTo($imageDiv);
                    // 先不做删除 $deleteButtion.appendTo($imageDiv);
                    $imageDiv.appendTo($li);
                    $li.appendTo(that.modelImageListUl);
                });
            }
        });
    };

    // done
    Settled.prototype.clearImageModel = function() {
        that.modelImageListUl.html("");
    }

    // done
    Settled.prototype.imageSwitch = function() {
        $(this).closest(".control-group").removeClass("error").removeClass("empty");
        $("#currentInput").val($(this).parent().find("input").attr("id"));

        that.clearImageModel();
        that.loadImageModel();

        $("#modal-image-selector").css("top", ($(window).height() - that.uploadModel.outerHeight()) / 2);
        $("#modal-image-selector").css("left", ($(window).width() - that.uploadModel.outerWidth()) / 2);
        $("#modal-image-selector").show();
    };
    
    // done
    Settled.prototype.imageSwitch_i = function() {
    	$(this).closest(".control-group").removeClass("error").removeClass("empty");
    	$("#currentInput").val($(this).parent().parent().parent().parent().find("input").attr("id"));
    	
    	that.clearImageModel();
    	that.loadImageModel();
    	
    	$("#modal-image-selector").css("top", ($(window).height() - that.uploadModel.outerHeight()) / 2);
    	$("#modal-image-selector").css("left", ($(window).width() - that.uploadModel.outerWidth()) / 2);
    	$("#modal-image-selector").show();
    };

    // done
    Settled.prototype.provinceChange = function() {
        var $this;
        $this = $(".province-select");
        return $.get(rrs.shopDomain + "/regions?parentId=0", function(data) {
            $.each(data.data, function(i, d) {
                $this.append("<option id='"+ d.id+"' value='" + d.code + "'>" + d.regionName + "</option>");
            });
            //$this.spin(false);
            if (provinceHtml != undefined && "" != provinceHtml) {
                $this.val(provinceHtml);
            }
            return that.cityChange();
        });
    };

    // done
    Settled.prototype.cityChange = function() {
        var $this, provinceId;
        $this = $(".city-select");
        provinceId =  $(".province-select option:selected").attr("id");
        $(".city-select option").remove();
        $(".region-select option").remove();
        //$this.spin("small");
        return $.get(rrs.shopDomain + "/regions?parentId=" + provinceId, function(data) {
            $.each(data.data, function(i, d) {
                return $(".city-select").append("<option id='"+ d.id+"' value='" + d.code + "'>" + d.regionName + "</option>");
            });
            if (cityHtml != undefined && "" != cityHtml) {
                $this.val(cityHtml);
            }
            return that.regionChange();
        });
    };

    //done
    Settled.prototype.regionChange = function() {
        var $this, cityId;
        $this = $(".region-select");
        cityId = $(".city-select option:selected").attr("id");
        $(".region-select option").remove();
        return $.get(rrs.shopDomain + "/regions?parentId=" + cityId, function(data) {
            $.each(data.data, function(i, d) {
                return $(".region-select").append("<option id='"+ d.id+"' value='" + d.code + "'>" + d.regionName + "</option>");
            });
            if (regionHtml != undefined && "" != regionHtml) {
                $this.val(regionHtml);
            }
        });
    };

    Settled.prototype.isWaterChange = function(){
    	var iswater = $(".iswater-select option:selected").attr("value");
    	if(iswater==0||iswater==4||iswater==6){
    		$("#brand-name-div-id").show();
    		$("#brand-name-span-id").show();
    		$("#brandName").attr("require",true);
    		if($("#brandPowerAttorney").val()==undefined || $("#brandPowerAttorney").val()==''){
    			$("#brand-div-id").show();
    			$("#brand-span-id").show();
    			$("#brand-div-id .js-image").attr("style","margin-left:0px;");
    			$("#brand-div-id li").hide();
    			$("#brand-div-id li").parent().find(".addbus").show();
    		}
    		//$("#ct-div-id").hide();
			//$("#ct-span-id").hide();
			$("#lt-div-id").hide();
			$("#lt-span-id").hide();
			//$('input:radio[name="customerType"]').attr("checked",false);
			$('input:radio[name="locationType"]').attr("checked",false);
    	}else if(iswater==5){
    		if($("#brandPowerAttorney").val()==undefined || $("#brandPowerAttorney").val()==''){
    			$("#brand-div-id").show();
    			$("#brand-span-id").show();
    			$("#brand-div-id .js-image").attr("style","margin-left:0px;");
    			$("#brand-div-id li").hide();
    			$("#brand-div-id li").parent().find(".addbus").show();
    		}
    		//$("#ct-div-id").hide();
			//$("#ct-span-id").hide();
			$("#lt-div-id").hide();
			$("#lt-span-id").hide();
			//$('input:radio[name="customerType"]').attr("checked",false);
			$('input:radio[name="locationType"]').attr("checked",false);
			$("#brand-name-div-id").hide();
    		$("#brand-name-span-id").hide();
    		$("#brandName").val('');
    		$("#brandName").attr("require",false);
    		$("#brand-name-div-id").removeClass("error").removeClass("empty");
    	}else{
    		$("#brand-name-div-id").hide();
    		$("#brand-name-span-id").hide();
    		$("#brand-div-id").hide();
    		$("#brand-span-id").hide();
    		$("#brand-div-id .js-image").attr("style","margin-left: 15px;");
    		$("#brandName").val('');
    		$("#brandPowerAttorney").val('');
    		$("#brand-div-id li").find("img").attr("src","");
    		$("#brand-div-id li").hide();
    		$("#brand-div-id li").parent().find(".addbus").show();
    		$("#brandName").attr("require",false);
    		$("#brand-div-id").removeClass("error").removeClass("empty");
    		$("#brand-name-div-id").removeClass("error").removeClass("empty");
    		if(iswater==1){
    			//$("#ct-div-id").show();
    			//$("#ct-span-id").show();
    			$("#lt-div-id").show();
    			$("#lt-span-id").show();
    			//if($('input[name="customerType"]:checked').val()==undefined){
    				//$("#lt-div-id label").show();
    			//}
    		}else{
    			//$("#ct-div-id").hide();
    			//$("#ct-span-id").hide();
    			$("#lt-div-id").hide();
    			$("#lt-span-id").hide();
    			//$('input:radio[name="customerType"]').attr("checked",false);
    			$('input:radio[name="locationType"]').attr("checked",false);
    		}
    	}
    	
    };
    
    
    Settled.prototype.organizeShop = function(form) {
        var businessId, city, isWater, shopName, companyName, email, phone, province, region, shop, street, taxRegisterNo;
        shopName = $("#shopName").val();
        companyName = $("#companyName").val();
        email = $("#email-input").val();
        //businessId = $('input[name="businessId"]:checked').val();
        isWater = $("select[name=isWater]").val();
        province = $("select[name=province]").val();
        city = $("select[name=city]").val();
        region = $("select[name=region]").val();
        street = $("#street").val();
        taxRegisterNo = $("#taxRegisterNo").val();
        return shop = {
        	name: shopName,
        	companyName: companyName,
        	email:email,
            businessId: 5,
            isWater: isWater,
            province: province,
            city: city,
            region: region,
            street: street,
            taxRegisterNo: taxRegisterNo
        };
    };
    Settled.prototype.organizeShopExtra = function(form) {
    	var companyType = $("select[name=companyType]").val();
    	var registeredCapital = $("#registeredCapital").val();
    	var companyStartAt = $("#companyStartAt").val();
    	var businessLicenceStartAt = $("#businessLicenceStartAt").val();
    	var businessLicenceEndAt = $("#businessLicenceEndAt").val();
    	var businessLicenceNo = $("#businessLicenceNo").val();
    	var zipCode = $("#zipCode").val();
    	var companyPhone = $("#companyPhone").val();
    	var taxpayersType = $("select[name=taxpayersType]").val()
    	var invoiceType = $('input[name="invoiceType"]:checked').val();;
    	var legalName = $("#legalName").val();
    	var idCard = $("#idCard").val();
    	var companyAccount = $("#companyAccount").val();
    	var companyAccountName = $("#companyAccountName").val();
    	var bankNumber = $("#bankNumber").val();
    	var brandPowerAttorney = $("#brandPowerAttorney").val();
    	var brandName = $("#brandName").val();
    	var shopCategory = "";
    	var shopCategoryArr=[];
    	$("input:checkbox[name=shopCategory]").each(function(){
			if($(this).prop("checked")){
				shopCategoryArr.push($(this).val());
			}
		});
		shopCategory=","+shopCategoryArr.join(",")+",";
		var customerType = 0;
		var locationType = $('input[name="locationType"]:checked').val();
		if(locationType==2){
			customerType = 1;
		}
		registeredCapital = registeredCapital*10000;//转成元
    	return extra = {
    			companyType: companyType,
    			registeredCapital: registeredCapital,
    			companyStartAtStr: companyStartAt,
    			businessLicenceStartAtStr: businessLicenceStartAt,
    			businessLicenceEndAtStr: businessLicenceEndAt,
    			businessLicenceNo: businessLicenceNo,
    			zipCode: zipCode,
    			companyPhone: companyPhone,
    			taxpayersType: taxpayersType,
    			invoiceType: invoiceType,
    			legalName: legalName,
    			idCard: idCard,
    			companyAccount: companyAccount,
    			companyAccountName: companyAccountName,
    			bankNumber: bankNumber,
    			brandPowerAttorney: brandPowerAttorney,
    			brandName:brandName,
    			shopCategory:shopCategory,
    			customerType:customerType,
    			locationType:locationType
    	};
    };

    Settled.prototype.organizeShopPaper = function() {
        var accountPermit, businessLicence, contractImage1, contractImage2, corporateIdentity, corporateIdentityB, organizationCode, shopPaperwork, taxCertificate;
        businessLicence = $("input[name=businessLicence]").val();
        taxCertificate = $("input[name=taxCertificate]").val();
        accountPermit = $("input[name=accountPermit]").val();
        organizationCode = $("input[name=organizationCode]").val();
        corporateIdentity = $("input[name=corporateIdentity]").val();
        corporateIdentityB = $("input[name=corporateIdentityB]").val();
        return shopPaperwork = {
            businessLicence: businessLicence,
            taxCertificate: taxCertificate,
            accountPermit: accountPermit,
            organizationCode: organizationCode,
            corporateIdentity: corporateIdentity,
            corporateIdentityB: corporateIdentityB
        };
    };

    Settled.prototype.applyFormSubmit = function(evt) {
        var shop, shopInfoDto, shopPaperwork, extra;
        evt.preventDefault();
        if(($("select[name=isWater]").val()==0||$("select[name=isWater]").val()==4||$("select[name=isWater]").val()==6)&&$("#brandPowerAttorney").val()==''){
        	$("#brand-div-id").addClass("error").addClass("empty");
        }
        if(($("select[name=isWater]").val()==0||$("select[name=isWater]").val()==4||$("select[name=isWater]").val()==6)&&$("#brandName").val()==''){
        	$("#brand-name-div-id").addClass("error").addClass("empty");
        }
        if($("select[name=isWater]").val()==5&&$("#brandName").val()==''){
        	$("#brand-name-div-id").removeClass("error").removeClass("empty");
        }
        var $errorInput = $("#apply-form").find(".error");
        var $errLen = $errorInput.length;
        if ($errLen > 0) {
            return;
        }
        if($('input[name="invoiceType"]:checked').val()==undefined){
        	$.sobox.alert("提示 ","请选择发票类型");
        	return;
        }
        if($('input[name="shopCategory"]:checked').val()==undefined){
        	$.sobox.alert("提示 ","请选择店铺所属类目");
        	return;
        }
        if($("#businessLicenceStartAt").val()>$("#businessLicenceEndAt").val()){
        	$.sobox.alert("提示","营业执照有效结束时间不能小于开始时间");
        	return;
        }
        if(($("select[name=isWater]").val()==1&&$('input[name="locationType"]:checked').val()==undefined)){
        	$.sobox.alert("提示","请选择门店类型");
        	return;
        }
        shop = that.organizeShop();
        shopPaperwork = that.organizeShopPaper();
        extra = that.organizeShopExtra();
        shopInfoDto = {
            shop: shop,
            shopPaperwork: shopPaperwork,
            extra:extra
        };
        $.ajaxSetup({
            contentType : 'application/json'
        });

        return $.ajax({
            url: rrs.shopDomain + "/settle/apply?"+getCSRFTokenParam(),
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(shopInfoDto),
            success: function(data) {
                if (data && data.success) {
                    return window.location.href = rrs.shopDomain + "/success.html";
                } else {
                    $.sobox.alert("申请店铺失败 ",data.message);
                    refrushCSRFToken(data.data);
                }
            },
            error: function(data) {
                $.sobox.alert("申请店铺失败 ","申请店铺失败 ");
            }
        });
    };

    return Settled;

})();